#!/usr/bin/env python3

'''
Author       : bopo
Date         : 2020-12-08 10:17:37
LastEditors  : bopo
LastEditTime : 2020-12-08 14:42:44
FilePath     : /stealer/stealer/adapter/tiktok.py
Description  :
'''
import json
import re

import requests

from . import BaseAdapter

headers = {
    "user-agent": 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.122 Safari/537.36'
}

download_headers = {
    "accept": "*/*",
    "accept-encoding": "identity;q=1, *;q=0",
    "accept-language": "zh-CN,zh;q=0.9,ja;q=0.8,en;q=0.7,zh-TW;q=0.6,de;q=0.5,fr;q=0.4,ca;q=0.3,ga;q=0.2",
    "range": "bytes=0-",
    "sec-fetch-dest": "video",
    "sec-fetch-mode": "no-cors",
    "sec-fetch-site": "cross-sit",
    "user-agent": 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.122 Safari/537.36'
}


class TikTokAdapter(BaseAdapter):

    @classmethod
    def get_prefix_pattern(cls) -> str:
        return 'vm\.tiktok\.com\/'

    @classmethod
    def make_url(cls, index) -> str:
        return f'http://vm.tiktok.com/{index}'

    def parse(self, url=None, header: bool = True):

        # 请求短链接，获得itemId和dytk
        res = requests.get(url, headers=headers)

        try:
            props = re.findall(
                r"(?<=<script id=\"__NEXT_DATA__\" type=\"application\/json\" crossorigin=\"anonymous\">)"
                r"(.*?)"
                r"(?=<\/script><script crossorigin=\"anonymous\")", res.text)
        except ValueError:
            return res.reason

        try:
            data = json.loads(str(props[0]))
            video_url = data['props']['pageProps']['videoData']['itemInfos']['video']['urls'][0]
        except (KeyError, IndexError) as e:
            raise e

        res = requests.get(url=video_url, headers=headers)
        text = res.content.decode('utf-8', 'ignore')

        index = text.index('vid:')
        video = text[index + 4: index + 36]

        link = f'https://api2.musical.ly/aweme/v1/playwm/?video_id={video}'
        data = {
            'link': link,
            'name': 'name',
            'meta': {
                'headers': download_headers
            }}
        return data


if __name__ == '__main__':
    TikTokAdapter().fetch('http://vm.tiktok.com/vwQ5YT')
